using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VOL.demo.IServices.wms.ShopOrder;
using VOL.Entity.DomainModels;

namespace VOL.WebApi.Controllers.demo
{
    [Route("api/[controller]")]
    [ApiController]
    public class ShopOrderController : ControllerBase
    {
        private readonly IShopOrderService _shopOrderService;

        public ShopOrderController(IShopOrderService shopOrderService)
        {
            _shopOrderService = shopOrderService;
        }

        /// <summary>
        /// 分页查询销售订单（基础版本）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>分页结果</returns>
        [HttpGet("page")]
        public async Task<IActionResult> GetPageList(int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await _shopOrderService.GetPageListAsync(pageIndex, pageSize);
                return Ok(new 
                { 
                    Code = 200, 
                    Data = result.Data, 
                    TotalCount = result.TotalCount,
                    Message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 分页查询销售订单联查结果（包含客户名称、部门名称、用户名称）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="shopOrderCode">销售单号（可选）</param>
        /// <param name="shopOrderDate">销售日期（可选，格式：yyyy-MM-dd）</param>
        /// <returns>分页结果</returns>
        [HttpGet("pageWithRelations")]
        public async Task<IActionResult> GetPageListWithRelations(
            int pageIndex = 1, 
            int pageSize = 10,
            string shopOrderCode = null,
            string shopOrderDate = null)
        {
            try
            {
                DateTime? parsedDate = null;
                if (!string.IsNullOrEmpty(shopOrderDate))
                {
                    if (DateTime.TryParse(shopOrderDate, out DateTime date))
                    {
                        parsedDate = date;
                    }
                    else
                    {
                        return BadRequest(new { Code = 400, Message = "销售日期格式不正确，请使用 yyyy-MM-dd 格式" });
                    }
                }

                var result = await _shopOrderService.GetPageListWithRelationsAsync(pageIndex, pageSize, shopOrderCode, parsedDate);
                return Ok(new 
                { 
                    Code = 200, 
                    Data = result.Data, 
                    TotalCount = result.TotalCount,
                    Message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 根据ID获取销售订单
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns>销售订单信息</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(long id)
        {
            try
            {
                var result = await _shopOrderService.GetByIdAsync(id);
                if (result == null)
                {
                    return NotFound(new { Code = 404, Message = "未找到该销售订单" });
                }
                
                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 更新销售订单
        /// </summary>
        /// <param name="entity">销售订单实体</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromBody] shopordermodel entity)
        {
            try
            {
                if (entity == null || entity.Id <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "无效的销售订单数据" });
                }
                
                var result = await _shopOrderService.UpdateAsync(entity);
                if (result)
                {
                    return Ok(new { Code = 200, Message = "更新成功" });
                }
                else
                {
                    return BadRequest(new { Code = 400, Message = "更新失败" });
                }
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"更新失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 删除销售订单
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(long id)
        {
            try
            {
                var result = await _shopOrderService.DeleteAsync(id);
                if (result)
                {
                    return Ok(new { Code = 200, Message = "删除成功" });
                }
                else
                {
                    return BadRequest(new { Code = 400, Message = "删除失败，可能该销售订单不存在或已审核" });
                }
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"删除失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 批量删除销售订单
        /// </summary>
        /// <param name="ids">销售订单ID列表</param>
        /// <returns>删除结果</returns>
        [HttpDelete("batch")]
        public async Task<IActionResult> BatchDelete([FromBody] long[] ids)
        {
            try
            {
                if (ids == null || ids.Length == 0)
                {
                    return BadRequest(new { Code = 400, Message = "请选择要删除的销售订单" });
                }
                
                var result = await _shopOrderService.DeleteRangeAsync(ids);
                if (result)
                {
                    return Ok(new { Code = 200, Message = "批量删除成功" });
                }
                else
                {
                    return BadRequest(new { Code = 400, Message = "批量删除失败" });
                }
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"批量删除失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取货品分页列表
        /// </summary>
        /// <param name="goodsCode">货品编号（可选）</param>
        /// <param name="goodsName">货品名称（可选）</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>货品分页结果</returns>
        [HttpGet("GetProductPageList")]
        public async Task<IActionResult> GetProductPageList(
            string goodsCode = null,
            string goodsName = null,
            int pageIndex = 1,
            int pageSize = 20)
        {
            try
            {
                var searchDto = new ProductSearchDto
                {
                    GoodsCode = goodsCode,
                    GoodsName = goodsName,
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };

                var result = await _shopOrderService.GetProductPageListAsync(searchDto);
                
                return Ok(new 
                { 
                    Code = 200, 
                    Data = result.Data, 
                    TotalCount = result.TotalCount,
                    Message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取部门级联列表
        /// </summary>
        /// <param name="departmentName">部门名称（可选）</param>
        /// <param name="departmentCode">部门编号（可选）</param>
        /// <param name="isTreeStructure">是否返回树形结构（默认true）</param>
        /// <param name="rootDepartmentId">根部门ID（可选，用于获取指定部门下的子树）</param>
        /// <returns>部门级联结果</returns>
        [HttpGet("GetDepartmentCascadeList")]
        public async Task<IActionResult> GetDepartmentCascadeList(
            string departmentName = null,
            string departmentCode = null,
            bool isTreeStructure = true,
            Guid? rootDepartmentId = null)
        {
            try
            {
                var searchDto = new DepartmentSearchDto
                {
                    DepartmentName = departmentName,
                    DepartmentCode = departmentCode,
                    IsTreeStructure = isTreeStructure,
                    RootDepartmentId = rootDepartmentId,
                    OnlyEnabled = true
                };

                var result = await _shopOrderService.GetDepartmentCascadeListAsync(searchDto);

                return Ok(new 
                { 
                    Code = 200, 
                    Message = "查询成功", 
                    Data = result,
                    Count = result.Count
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询部门级联失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取部门树形选择器数据（专用于前端选择器组件）
        /// </summary>
        /// <param name="departmentName">部门名称（可选）</param>
        /// <returns>部门树形选择器数据</returns>
        [HttpGet("GetDepartmentTreeSelector")]
        public async Task<IActionResult> GetDepartmentTreeSelector(string departmentName = null)
        {
            try
            {
                var searchDto = new DepartmentSearchDto
                {
                    DepartmentName = departmentName,
                    IsTreeStructure = true,
                    OnlyEnabled = true
                };

                var departments = await _shopOrderService.GetDepartmentCascadeListAsync(searchDto);

                // 转换为前端选择器需要的格式
                var selectorData = departments.Select(d => new
                {
                    value = d.DepartmentId,
                    label = d.DepartmentName,
                    code = d.DepartmentCode,
                    level = d.Level,
                    path = d.DepartmentPath,
                    children = ConvertToSelectorFormat(d.Children)
                }).ToList();

                return Ok(new 
                { 
                    Code = 200, 
                    Message = "查询成功", 
                    Data = selectorData
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询部门树形选择器数据失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 递归转换部门数据为选择器格式
        /// </summary>
        private object ConvertToSelectorFormat(List<DepartmentCascadeDto> departments)
        {
            return departments.Select(d => new
            {
                value = d.DepartmentId,
                label = d.DepartmentName,
                code = d.DepartmentCode,
                level = d.Level,
                path = d.DepartmentPath,
                children = ConvertToSelectorFormat(d.Children)
            }).ToList();
        }

        /// <summary>
        /// 获取用户下拉选择列表
        /// </summary>
        /// <param name="userName">用户名称（可选，模糊查询）</param>
        /// <param name="departmentId">部门ID（可选）</param>
        /// <param name="roleId">角色ID（可选）</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>用户下拉选择结果</returns>
        [HttpGet("users/select")]
        public async Task<IActionResult> GetUserSelectList(
            string userName = null,
            Guid? departmentId = null,
            int? roleId = null,
            int pageIndex = 1,
            int pageSize = 50)
        {
            try
            {
                var searchDto = new UserSearchDto
                {
                    UserName = userName,
                    DepartmentId = departmentId,
                    RoleId = roleId,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    OnlyEnabled = true
                };

                var result = await _shopOrderService.GetUserSelectListAsync(searchDto);

                return Ok(new 
                { 
                    Code = 200, 
                    Message = "查询成功", 
                    Data = result.Data,
                    TotalCount = result.TotalCount
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询用户列表失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 添加销售订单和销售订单明细（使用事务）
        /// </summary>
        /// <param name="createDto">销售订单和销售订单明细创建DTO</param>
        /// <returns>添加结果</returns>
        [HttpPost("add-with-details")]
        public async Task<IActionResult> AddWithDetails([FromBody] ShopOrderWithDetailsCreateDto createDto)
        {
            try
            {
                Console.WriteLine("=== Controller层开始处理销售订单添加 ===");
                Console.WriteLine($"接收到的数据: {System.Text.Json.JsonSerializer.Serialize(createDto)}");
                
                if (createDto == null)
                {
                    Console.WriteLine("❌ 失败原因: 请求体为空");
                    return BadRequest(new { Code = 400, Message = "请求数据不能为空" });
                }

                if (createDto.ShopOrder == null)
                {
                    Console.WriteLine("❌ 失败原因: 销售订单信息为空");
                    return BadRequest(new { Code = 400, Message = "销售订单信息不能为空" });
                }

                if (createDto.ShopOrderDetails == null || !createDto.ShopOrderDetails.Any())
                {
                    Console.WriteLine("❌ 失败原因: 销售订单明细为空");
                    return BadRequest(new { Code = 400, Message = "销售订单明细不能为空，至少需要一条明细" });
                }

                Console.WriteLine($"销售订单编号: {createDto.ShopOrder.ShopOrderCode}");
                Console.WriteLine($"销售订单明细数量: {createDto.ShopOrderDetails.Count}");

                var result = await _shopOrderService.AddWithDetailsAsync(createDto);

                if (result)
                {
                    Console.WriteLine("✅ 销售订单添加成功");
                    return Ok(new 
                    { 
                        Code = 200, 
                        Message = "销售订单添加成功",
                        Data = new { Success = true }
                    });
                }
                else
                {
                    Console.WriteLine("❌ 销售订单添加失败");
                    return BadRequest(new { Code = 500, Message = "销售订单添加失败" });
                }
            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine($"❌ 参数异常: {ex.Message}");
                return BadRequest(new { Code = 400, Message = ex.Message });
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine($"❌ 参数异常: {ex.Message}");
                return BadRequest(new { Code = 400, Message = ex.Message });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ Controller层异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"销售订单添加失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取所有客户简单列表（仅ID和名称，用于下拉框选择）
        /// </summary>
        /// <returns>客户简单列表</returns>
        [HttpGet("customers")]
        public async Task<IActionResult> GetAllCustomers()
        {
            try
            {
                var customers = await _shopOrderService.GetAllCustomersSimpleAsync();

                return Ok(new 
                { 
                    Code = 200, 
                    Message = "查询成功", 
                    Data = customers
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询客户列表失败: {ex.Message}" });
            }
        }
    }
}
